package com.freely.ui.fragments;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.request.RequestOptions;
import com.freely.R;
import com.freely.R2;
import com.freely.component.BaseRecyclerViewAdapter;
import com.freely.component.activity.FreelyApplication;
import com.freely.component.activity.TitleFragment;
import com.freely.data.database.FreelyDatabase;
import com.freely.data.entities.Group;
import com.freely.data.entities.User;
import com.freely.data.managerUtils.FreelySharedPreferences;
import com.freely.data.repository.entities.GroupChatMessage;
import com.freely.ui.util.ErrorUtil;
import com.freely.ui.viewModel.GroupChatMessageViewModel;

import java.util.Date;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okio.ByteString;

public class GroupChatMessageFragment extends TitleFragment {
    private static final String TAG = "GCMFragment";
    private GroupChatMessageViewModel mViewModel;
	private long groupId;
	private User user;
	private BaseRecyclerViewAdapter adapter;

    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R2.id.send_text)
    EditText sendText;
    @BindView(R2.id.send)
    Button send;

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_group_chat_message, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
		FreelyDatabase.getInstance()
				.userDAO()
				.queryUserByUserId(FreelySharedPreferences.getInstance().getUserId())
				.subscribeOn(Schedulers.io())
				.subscribe(new SingleObserver<User>() {
					Disposable disposable;

					@Override
					public void onSubscribe(Disposable d) {
						disposable = d;
					}

					@Override
					public void onSuccess(User u) {
						user = u;
						disposable.dispose();
					}

					@Override
					public void onError(Throwable e) {
						ErrorUtil.errorHint(e);
						disposable.dispose();
					}
				});
        init();
    }

    private void init() {
		groupId = getArguments().getLong(Group.group_id);
        //viewModel 初始化
        mViewModel = ViewModelProviders.of(this).get(GroupChatMessageViewModel.class);
        //recyclerView 设置参数
        Log.d(TAG, "init: recycler view="+recyclerView);
		LinearLayoutManager manager = new LinearLayoutManager(getContext());
		recyclerView.setLayoutManager(manager);
		recyclerView.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
			Log.d(TAG, "init: 布局更改");
			if (bottom >= oldBottom || adapter.getItemCount() <= 0) {
				Log.d(TAG, "init: 条件不满足");
				return;
			}
			Log.d(TAG, "init: 位置调整");
			recyclerView.post(() -> recyclerView.scrollToPosition(adapter.getItemCount() - 1));
		});
		adapter = new BaseRecyclerViewAdapter() {
			@Override
			public int getItemCount() {
				List<GroupChatMessage> messages = mViewModel.getGroupMessageList().getValue();
				return messages == null ? 0 : messages.size();
			}
		};
		adapter.getView(position -> {
			List<GroupChatMessage> messages = mViewModel.getGroupMessageList().getValue();
			GroupChatMessage message = messages.get(position);
			long userId = user.getUserId();
			int viewType;
			if (userId == message.getUserId()) {
				viewType = R.layout.fragment_group_chat_message_recycler_right;
			} else {
				viewType = R.layout.fragment_group_chat_message_recycler_left;
			}
			return viewType;
		});
		adapter.onBindView((holder, position) -> {
			long userId = user.getUserId();
			List<GroupChatMessage> messages = mViewModel.getGroupMessageList().getValue();
			GroupChatMessage message = messages.get(position);
			ImageView userHeadIcon = holder.getView(R.id.user_head_image);
			TextView displayMessage = holder.getView(R.id.message);
			displayMessage.setText(message.getMessage());
			if (message.getUserHeadIcon().isEmpty()) {
				return;
			}
			if (userId == message.getUserId() && userHeadIcon.getDrawable() != null) {
				return;
			}
			if (userId != message.getUserId()) {
				TextView userName = holder.getView(R.id.user_name);
				userName.setText(message.getUserName());
			}
			Single.create((SingleOnSubscribe<RequestBuilder<Drawable>>) emitter -> {
				RequestBuilder<Drawable> builder = Glide.with(GroupChatMessageFragment.this)
						.load(ByteString.decodeBase64(message.getUserHeadIcon()).toByteArray())
						.apply(RequestOptions.circleCropTransform());
				emitter.onSuccess(builder);
			})
					.subscribeOn(Schedulers.computation())
					.observeOn(AndroidSchedulers.mainThread())
					.subscribe(new SingleObserver<RequestBuilder<Drawable>>() {
						Disposable disposable;

						@Override
						public void onSubscribe(Disposable d) {
							disposable = d;
						}

						@Override
						public void onSuccess(RequestBuilder<Drawable> drawableRequestBuilder) {
							drawableRequestBuilder.into(userHeadIcon);
							disposable.dispose();
						}

						@Override
						public void onError(Throwable e) {
							ErrorUtil.errorHint(e);
							disposable.dispose();
						}
					});

		});
		recyclerView.setAdapter(adapter);
		//聊天消息查询回调
		mViewModel.getGroupMessageList().observe(this, listSingle -> {
			recyclerView.scrollToPosition(adapter.getItemCount() - 1);
			adapter.notifyDataSetChanged();
		});
		List<GroupChatMessage> list = mViewModel.getGroupMessageList().getValue();
		//加载聊天消息
		mViewModel.loadGroupChatMessage(
				groupId,
				list == null ? 0 : list.size(),
				50
		);
		//接受到新消息
		mViewModel.getNewMessage().observe(this, new Observer<GroupChatMessage>() {
			@Override
			public void onChanged(GroupChatMessage groupChatMessage) {
				mViewModel.getGroupMessageList().getValue().add(groupChatMessage);
				int position = adapter.getItemCount() - 1;
				recyclerView.scrollToPosition(position);
				adapter.notifyItemInserted(position);
			}
		});
    }

	@OnClick(R2.id.send)
	void sendMessage() {
		Log.d(TAG, "sendMessage: ----------开始发送消息----------");
		Log.d(TAG, "sendMessage: 界面显示");
		Date date = new Date(System.currentTimeMillis());
		String sendText = this.sendText.getText().toString();
		GroupChatMessage message = new GroupChatMessage();
		message.setMessage(sendText);
		message.setTime(date);
		message.setUserId(user.getUserId());
		message.setUserHeadIcon(user.getUserImage());
		mViewModel.getGroupMessageList().getValue().add(message);
		recyclerView.scrollToPosition(adapter.getItemCount() - 1);
		adapter.notifyItemInserted(adapter.getItemCount() - 1);
		mViewModel.sendMessage(user.getUserId(), groupId, date, sendText);
		this.sendText.setText(null);
    }
    @Override
    public CharSequence getTitle() {
        return FreelyApplication.getContext().getString(R.string.group_chat);
    }

}
